Majority Element

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

Solution:

  1. public class Solution {
  2. public int majorityElement(int[] nums) {
  3. Integer m = null;
  4. int c = 0;
  5. for (int i = 0; i < nums.length; i++) {
  6. if (m != null && m == nums[i]) {
  7. c++;
  8. } else if (c == 0) {
  9. m = nums[i];
  10. c = 1;
  11. } else {
  12. c--;
  13. }
  14. }
  15. c = 0;
  16. for (int i = 0; i < nums.length; i++) {
  17. if (m != null && m == nums[i]) {
  18. c++;
  19. }
  20. }
  21. if (c > nums.length / 2) {
  22. return m;
  23. } else {
  24. return -1;
  25. }
  26. }
  27. }